const db = require("../libs/DBHelper");
const moment = require("moment");
const jwt = require("jwt-simple");
const md5 = require("md5");

class UserController {
    //post 登录
    async login(req, res) {
            let sql = "SELECT `uId`,`name`,`createDate` FROM `userinfo`  WHERE `name`=? AND `password`=?";
            let params = [
                req.body.name,
                req.body.password
            ]
            let results = await db.exec(sql, params); //查询是返回数组
            let isLogin = results && results.length >= 1;
            if (isLogin) {

                //登录成功,就生成token
                var token = jwt.encode(results[0], md5("cs2201"))

                res.json({
                    code: 200,
                    msg: "登录成功!",
                    data: results[0],
                    token
                })
            } else {
                res.json({
                    code: 401,
                    msg: "用户名或密码错误!"
                })
            }
        }
        //post 注册
    async register(req, res) {
        let sql = "INSERT INTO `userinfo`(`name`,`password`,`createDate`)VALUES(?,?,?);";
        let params = [
            req.body.name,
            req.body.password,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]


        try {
            let results = await db.exec(sql, params) // 插入,修改,删除,返回的 受影响行数
            let isReg = results && results.affectedRows >= 1; // affectedRows  受影响行数

            res.json({
                code: isReg ? 200 : 400, // 400
                msg: isReg ? "注册成功" : "注册失败!"
            })
        } catch (error) {
            res.json({
                code: 400, // 400
                msg: "注册失败!",
                error
            })
        }
    }
}


module.exports = new UserController;


//
//
// post    /api/user    注册
// get     /api/user    查询

// delete  /api/user
// put